package com.example.back.Controller;

import com.example.back.Annotation.UserLoginToken;
import com.example.back.Entity.MessageItem;
import com.example.back.Entity.Talker;
import com.example.back.Repository.MessageRepository;
import com.example.back.Repository.TalkerRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 消息模块
 */
@Slf4j
@UserLoginToken
@RestController
@RequestMapping("message")
public class MessageController {

    @Autowired
    private MessageRepository messageRepository;
    @Autowired
    private TalkerRepository talkerRepository;

    //发消息
    @UserLoginToken
    @PostMapping("")
    public boolean addNewMessage(@RequestBody MessageItem messageItem) {
        try {
            messageItem.setMessageSenderDate(new Date());
            messageRepository.save(messageItem);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //获取全部未读消息
    @UserLoginToken
    @GetMapping("unread/{userId}/{otherId}")
    public List<MessageItem> findAllUnreadMessage(@PathVariable("userId") long userId,
                                                  @PathVariable("otherId") long otherId) {
        Sort sort = Sort.by(Sort.Direction.ASC, "messageSenderDate");
        List<MessageItem> returnList = messageRepository.findAllByMessageReadAndMessageReceiverIdAndMessageSenderId(sort, false, userId, otherId);
        messageRepository.setMessageReadByMessageSenderIdAndMessReceiverId(otherId, userId);
        return returnList;
    }

    //删除聊天
    @UserLoginToken
    @DeleteMapping("/talker/{talkerId}")
    public void deleteTalkerByTalkerId(@PathVariable("talkerId") long talkerId) {
        talkerRepository.deleteById(talkerId);
    }

    //增加新聊天
    @UserLoginToken
    @PostMapping("talker")
    public boolean addNewTalker(@RequestBody Talker talker) {
        try {
            //如果当前聊天已经存在了，则不可以新建
            if (talkerRepository.findTalkerByUserIdAndAndOtherId(talker.getUserId(), talker.getOtherId()) != null)
                return false;
            talker.setLatestTime(new Date());
            log.info(talker.getOtherAvatarUUID());
            talkerRepository.save(talker);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //获取全部消息
    @UserLoginToken
    @GetMapping("/list/{userId}/{otherId}")
    public List<MessageItem> findAllByUserId(@PathVariable("userId") long userId,
                                             @PathVariable("otherId") long otherId) {
        //获取对方发给自己的--获取全部
        List<MessageItem> resultList = messageRepository.findAllByMessageReceiverIdAndMessageSenderId(userId, otherId);
        //获取自己发给对方的--获取全部
        resultList.addAll(messageRepository.findAllByMessageReceiverIdAndMessageSenderId(otherId, userId));
        //把对方发给我的均设为已读
        messageRepository.setMessageReadByMessageSenderIdAndMessReceiverId(otherId, userId);
        //依照发送时间来排序
        resultList.sort(Comparator.comparing(MessageItem::getMessageSenderDate));
        return resultList;
    }

    //根据userId返回聊天列表
    @UserLoginToken
    @GetMapping("/talkList/{uid}")
    public List<Talker> findAllTalkerUserAndOther(@PathVariable("uid") long uid) {
        List<Talker> talkers = talkerRepository.findAllByOtherId(uid);
        talkers.addAll(talkerRepository.findAllByUserId(uid));
        //根据最后发送时间排序
        talkers.sort(Comparator.comparing(Talker::getLatestTime));
        return talkers;
    }

    //根据ID查询talker
    @UserLoginToken
    @GetMapping("/talk/{tId}")
    public Talker findTalkByTalkerId(@PathVariable("tId") long tId) {
        return talkerRepository.findTalkerByTalkerId(tId);
    }

    //更新最新聊天时间
    @UserLoginToken
    @PatchMapping("/talker/{talkerId}/{latestTime}")
    public boolean updateLatestTime(@PathVariable("talkerId") long talkerId,
                                    @PathVariable("latestTime") Date latestTime) {
        try {
            Talker Ttalker = talkerRepository.findTalkerByTalkerId(talkerId);
            Ttalker.setLatestTime(latestTime);
            talkerRepository.save(Ttalker);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
